<template>
    <a-page-header
            style="border: 1px solid rgb(235, 237, 240)"
            :title="title"
            @back="handleTurnBack"
        />
    <div class="search">
        <a-input
            v-model:value="searchData.search"
            placeholder="搜索内容"
            style="width: 200px; color: gray; margin-left: 50px;"
            size="large"
            load
        />
        <div style="color: grey; font-size: large; margin-left: 50px; margin-top: 10px;">创建日期：</div>
        <a-range-picker v-model:value="dateRange" show-time style="margin-left: 10px;" />
        <div style="color: grey; font-size: large; margin-left: 50px; margin-top: 10px;">排序项：</div>
        <a-select
            v-model:value="searchData.order"
            placeholder="选择排序项"
            :options="ordersAll"
            style="width: 200px; margin-left: 10px;"
        />
        <a-radio-group v-model:value="searchData.orderType" style="margin-left: 20px;">
            <a-radio style=" display: flex;" value="asc">正序</a-radio>
            <a-radio style=" display: flex;" value="desc">倒序</a-radio>
        </a-radio-group>
        <a-button size="large" style="margin-left: 50px;" @click="search(1)">搜索</a-button>
    </div>
    <br />
    <div style="margin-top: 20px; width: 1400px; margin-left: 300px;">
        <a-list item-layout="vertical" size="large" :pagination="pagination" :data-source="listData" style="width: 1000px; margin-left: 200px; margin-bottom: 50px;">
            <template #renderItem="{ item, index }" style="align: left;">
                <a-list-item key="item.title">
                    <template #actions>
                        <span>
                            <div @click="handleLikeOrDisLike(item.id, item.index, item.isLiked)">
                                <component v-if="item.isLiked" :is="LikeTwoTone" style="margin-right: 8px" two-tone-color="#eb2f96"/>
                                <component v-else :is="LikeTwoTone" style="margin-right: 8px" two-tone-color=""/>
                                {{ item.likeCount }}
                            </div>
                        </span>
                        <span>
                            <div @click="">
                                <component :is="MessageTwoTone" style="margin-right: 8px" />
                                0
                            </div>
                        </span>
                    </template>
                    <template #extra>
                    </template>
                    <a-list-item-meta :description="item.description" style="text-align: left;">
                        <template #title>
                            <a>{{ item.title }}</a>
                        </template>
                        <template #avatar><a-avatar :src="item.avatar" /></template>
                    </a-list-item-meta>
                    <div style="font-size: medium; margin-left: 20px; text-align: left;">{{ item.content }}</div>
                    <span v-for="pic in item.pics" :key="pic">
                        <img :src="pic" height="50px" width="50px"/>
                    </span>
                </a-list-item>
                <a-collapse v-model:activeKey="activeKey" ghost @change="handleOpenReplies(item.id)">
                    <a-collapse-panel :key="item.id" header="评论">
                        <a-list
                            class="comment-list"
                            :header="`${replyDataList.get(item.id)?.length != undefined ? replyDataList.get(item.id)?.length : 0} replies`"
                            item-layout="horizontal"
                            :data-source="replyDataList.get(item.id)"
                            :pagination="replyPagenations.get(item.id)"
                        >
                            <template #renderItem="{ item }">
                                <a-list-item>
                                    <a-comment :author="item.author" :avatar="item.avatar">
                                        <template #actions>
                                            <span @click="replySomebody(item.creator, item.author, index)"> reply </span>
                                        </template>
                                        <template #content>
                                            <p>
                                            {{ item.content }}
                                            </p>
                                        </template>
                                        <template #datetime style="display: flex;">
                                            <div>{{ item.gmtCreated }}</div>
                                            <div v-if="item.replyUserName != ''">回复 {{ item.replyUserName }}</div>
                                        </template>
                                    </a-comment>
                                </a-list-item>
                            </template>
                        </a-list>
                        <a-comment v-if="!isLocked" style="width: 700px;">
                            <template #avatar>
                                <a-avatar :src="avatar" :alt="username" />
                            </template>
                            <template #content>
                            <a-form-item>
                                <a-textarea v-model:value="replies[item.index].content" :rows="1" />
                                回复: {{ replies[item.index].toName }}
                            </a-form-item>
                            <a-form-item>
                                <a-button html-type="submit" type="primary" @click="addReply(item.id, item.index)">
                                    评论
                                </a-button>
                            </a-form-item>
                            </template>
                        </a-comment>
                    </a-collapse-panel>
                </a-collapse>
                <a-divider style="height: 2px; background-color: black;" />
            </template>
        </a-list>
    </div>
    <br />
    <a-comment v-if="!isLocked" style="width: 1000px; margin-left: 500px;">
        <template #avatar>
            <a-avatar :src="avatar" :alt="username" />
        </template>
        <template #content>
        <a-form-item>
            <a-textarea v-model:value="content" :rows="4" />
        </a-form-item>
        <a-form-item>
            <a-upload
                v-model:file-list="fileList"
                list-type="picture-card"
                :max-count="10"
                @preview="handlePreview"
                :before-upload="beforeUploadPic"
                :customRequest="handleUpload"
                @remove="handleRemove"
            >
                <div>
                    <plus-outlined />
                    <div style="margin-top: 8px">Upload</div>
                </div>
            </a-upload>
            <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
        </a-form-item>
        <a-form-item>
            <a-button html-type="submit" type="primary" @click="addContent">
                发布
            </a-button>
        </a-form-item>
        </template>
    </a-comment>
</template>

<script lang="ts">
export default {
    name: 'TopicDetail'
}
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch } from 'vue';
import type { Dayjs } from 'dayjs';
import { searchContentList } from '@/api/forum_api'
import { MessageTwoTone, LikeTwoTone, StarTwoTone, ManOutlined } from '@ant-design/icons-vue';
import { message, UploadProps } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import router from '@/router';
import { likeContent, disLikeContent, newContent, newReply, getReplyList } from '@/api/forum_api'

const data = [
  {
    title: 'Ant Design Title 1',
  },];
const title = ref<string>('');
const listData =  ref<Record<string, any>[]>([]);"Han Solo"
interface SearchData {
    topicId:number,
    search: string,
    beginTime: any,
    EndTime: any,
    order: string,
    orderType: string
}
const searchData = reactive<SearchData>({
    topicId: 0,
    search: '',
    beginTime: null,
    EndTime: null,
    order: 'likeCount',
    orderType: 'desc'
})
type RangeValue = [Dayjs, Dayjs];
const dateRange = ref<RangeValue>();
const ordersAll = ref<{label: string, value: string, disabled: boolean}[]>([
{label: '创建时间', value: 'gmtCreated', disabled: false},
{label: '点赞数', value: 'likeCount', disabled: false},
])
const pagination = {
    onChange: (page: number) => {
        pagination.current = page
        search(page)
    },
    current: 1,
    pageSize: 5,
    total: 0,
};
const activeKey = ref<number[]>([]);
const content = ref<string>('');
const route = useRoute()
const avatar = localStorage.getItem('avatar')
const username = localStorage.getItem('username')
const fileList = ref<any[]>([]);
const picFiles = ref<any[]>([]);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const isLocked = ref<boolean>(false)
interface reply {
    content: string,
    to: string,
    toName: string,
}
const replies = ref<reply[]>([]);
const replyDataList = ref<Map<any, any[]>>(new Map());
const replyPagenations = ref<Map<any, any>>(new Map());

onMounted(async () => {
    title.value = String(route.params.title)
    searchData.topicId = Number(route.params.topicId)
    isLocked.value = String(route.params.isLocked) != 'N'
    for (let i = 0; i < pagination.pageSize; i++) {
        replies.value.push({content:'', to:'', toName: ''})
    }
    await search(1)
});
const search = async (page:number) => {
    if (dateRange.value != undefined && dateRange.value.length == 2) {
        searchData.beginTime = dateRange.value?.[0].format('YYYY-MM-DD HH:mm:ss')
        searchData.EndTime = dateRange.value?.[1].format('YYYY-MM-DD HH:mm:ss')
    }
    await searchContentList(searchData, page, 5)
    .then(resp => {
        pagination.total = resp.data.total
        replyPagenations.value = new Map();
        replyDataList.value = new Map();
        activeKey.value = [];
        listData.value = []
        for (let i = 0; i < resp.data.list.length; i++) {
            let data = {
                index: i,
                title: resp.data.list[i].creatorName,
                description: resp.data.list[i].gmtCreated,
                id: resp.data.list[i].id,
                likeCount: resp.data.list[i].likeCount,
                content: resp.data.list[i].content,
                isLiked: resp.data.list[i].isLiked,
                pics: resp.data.list[i].pics,
                avatar: resp.data.list[i].creatorAvatar
            }
            listData.value.push(data)
            replies.value[i].content = ''
            replies.value[i].to = ''
            replies.value[i].toName = ''
        }
        searchData.search = ""
        searchData.beginTime = null
        searchData.EndTime = null
        dateRange.value = undefined;
    })
    .catch(error => {})
};
const handleTurnBack = () => {
    router.back()
}
const handleLikeOrDisLike = async (id:number, index:number, isLiked:boolean) => {
    if (isLiked) {
        await disLikeContent(id)
        .then(resp => {
            listData.value[index].likeCount -= 1
            message.info("取消成功!")
        })
        .catch(err => {})
    } else {
        await likeContent(id)
        .then(resp => {
            listData.value[index].likeCount += 1
            message.info("点赞爆棚！")
        })
        .catch(err => {})
    }
    listData.value[index].isLiked = !listData.value[index].isLiked
};
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handlePreview = async (file:any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};
const beforeUploadPic: UploadProps['beforeUpload'] = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
        message.error('Image must smaller than 10MB!');
    }
    return isJpgOrPng && isLt10M;
};
const handleUpload = (info:any) => {
  picFiles.value.push(info.file)
  console.log(picFiles.value)
  fileList.value[fileList.value?.length-1].status = "done"
};
const handleRemove: UploadProps['onRemove'] = file => {
    let index = -1
    for (let i = 0, l = fileList.value.length; i < l; i++) {
        if (fileList.value[i].uid == file.uid) {
            index = i
        } 
    }
    fileList.value.splice(index, 1);
    let index2 = -1
    for (let i = 0, l = picFiles.value.length; i < l; i++) {
        if (picFiles.value[i].uid == file.uid) {
            index2 = i
        } 
    }
    picFiles.value.splice(index2, 1);
    console.log(picFiles.value)
};
const addContent = async (values: any) => {
    console.log(picFiles)
    const formData = new FormData();
    formData.append("topicId", searchData.topicId.toString())
    formData.append("content", content.value)
    formData.append("picCount", picFiles.value.length.toString())
    for (let i = 0; i < picFiles.value.length; i++) {
        formData.append("pic"+i, picFiles.value[i])
    }
    await newContent(formData)
    .then(resp => {
        message.info("新建成功")
        search(pagination.current)
    })
    .catch(err => {})
};
const replySomebody = (uid:string, username:string, index:number) => {
    replies.value[index].to = uid
    replies.value[index].toName = username
}
const addReply = async (contentId: number, replyIndex: number) => {
    const data = {
        "contentId": contentId,
        "content": replies.value[replyIndex].content,
        "replyUser": replies.value[replyIndex].to
    }
    await newReply(data)
    .then(resp => {
        message.info("评论成功！")
        replies.value[replyIndex].content = ''
        replies.value[replyIndex].to = ''
        searchReply(contentId, 1, 5)
    })
    .catch(err => {})
};
const searchReply = async (contentId:number, page:number, pageSize:number) => {
    await getReplyList(contentId, page, pageSize)
    .then(resp => {
        let arr: any[] = []
        for (let i = 0, l = resp.data.list.length; i < l; i++) {
            let data = {
                creator: resp.data.list[i].creator,
                author: resp.data.list[i].creatorName,
                avatar: resp.data.list[i].creatorAvatar,
                content: resp.data.list[i].content,
                gmtCreated: resp.data.list[i].gmtCreated,
                replyUserName: resp.data.list[i].replyUserName
            }
            arr.push(data)
        }   
        replyDataList.value.set(contentId, arr)
    })
    .catch(err => {})
}
const handleOpenReplies = async (contentId:number) => {
    if (replyDataList.value.has(contentId)) {
        return
    }
    if (replyPagenations.value.get(contentId) == undefined) {
        replyPagenations.value.set(contentId, {
            page: 1, 
            pageSize: 5, 
            onChange: (page: number) => {
                replyPagenations.value.get(contentId).page = page
                searchReply(contentId, page, 5)
            },
        })
    }
    await searchReply(contentId, 1, 5)
}
</script>

<style scoped>
.search {
  display: flex;
  margin-top: 20px;
  margin-left: 200px;
}
</style>